<?php
header('Content-Type: text/html; charset=UTF-8');
require 'crawl.php';
require 'database.php';
$db = new DB();

// Select games ID
$Qry = 'SELECT id, crawl_url
		FROM games
		WHERE done = 0
		ORDER BY id DESC
		LIMIT 10';
$res = $db->fetchAll($Qry);

foreach ($res as $key=>$value) {
	crawl($value['id'], $value['crawl_url']);
}

function crawl($id, $url) {
	global $db;
	$sth = array("'", '=', '"');

	$html = file_get_html($url);

	// Game
	$game_file = preg_replace('/\<!DOCTYPE html\>(.*?)gameSwf/si', '', $html);
	$game_file = preg_replace('/\;(.*?)\<\/html\>/si', '', $game_file);
	$game_file = str_replace($sth, '', $game_file);
	$embed = trim($game_file);

	// Width
	$width = preg_replace('/\<!DOCTYPE html\>(.*?)gameWidth/si', '', $html);
	$width = preg_replace('/\;(.*?)\<\/html\>/si', '', $width);
	$width = str_replace($sth, '', $width);
	$width = (int)$width;
	
	// Height
	$height = preg_replace('/\<!DOCTYPE html\>(.*?)gameHeight/si', '', $html);
	$height = preg_replace('/\;(.*?)\<\/html\>/si', '', $height);
	$height = str_replace($sth, '', $height);
	$height = (int)$height;

	// jogo info descricao
	if ($html->find('div.content', 0))
		$info = $html->find('div.content', 0)->innertext;

	$desc = trim($info);
	$desc = str_replace('http://www.gamepilot.com/games/ninja', '/', $desc);

//echo $embed . '<br />' . $desc;
//exit();

	$query = '';
	if ($embed) {
		$condition = 'id = ' . $id;

		$games = array(
				'url'=>$embed,
				'width'=>$width,
				'height'=>$height,
				'done'=>1,
				'active'=>0
		);
		$data = array(
				'infomation'=>$desc
		);

		$db->update('games', $games, $condition);
		$db->update('games_description', $data, $condition);

		echo '<div>Game ID ' . $id . ' ==> Okay.</div>';
	}

// 	return $query;
}